// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//

package cmd

import (
	"fmt"
	"os"
	"strings"

	"github.com/kumose/errors"
	"github.com/kumose/kmopt/pkg/environment"
	"github.com/kumose/kmopt/pkg/localdata"
	"github.com/kumose/kmopt/pkg/utils"
	"github.com/spf13/cobra"
)

func newUninstallCmd() *cobra.Command {
	var all, self bool
	cmdUnInst := &cobra.Command{
		Use:   "uninstall <component1>:<version>",
		Short: "Uninstall components or versions of a component",
		Long: `If you specify a version number, uninstall the specified version of
the component. You must use --all explicitly if you want to remove all
components or versions which are installed. You can uninstall multiple
components or multiple versions of a component at once. The --self flag
which is used to uninstall kmopt.

  # Uninstall kmopt
  kmopt uninstall --self

  # Uninstall the specific version a component
  kmopt uninstall tidb:v3.0.10

  # Uninstall all version of specific component
  kmopt uninstall tidb --all

  # Uninstall all installed components
  kmopt uninstall --all`,
		RunE: func(cmd *cobra.Command, args []string) error {
			env := environment.GlobalEnv()
			if self {
				deletable := []string{"storage/cluster/packages", "components", "manifests", "manifest", "bin"}
				for _, dir := range deletable {
					if err := os.RemoveAll(env.Profile().Path(dir)); err != nil {
						return errors.Trace(err)
					}
					fmt.Printf("Remove directory '%s' successfully!\n", env.Profile().Path(dir))
				}
				fmt.Printf("Uninstalled KMOPT successfully! (User data reserved, you can delete '%s' manually if you confirm userdata useless)\n", env.Profile().Root())
				return nil
			}
			switch {
			case len(args) > 0:
				return removeComponents(env, args, all)
			case len(args) == 0 && all:
				if err := os.RemoveAll(env.LocalPath(localdata.ComponentParentDir)); err != nil {
					return errors.Trace(err)
				}
				fmt.Println("Uninstalled all components successfully!")
				return nil
			default:
				return cmd.Help()
			}
		},
	}
	cmdUnInst.Flags().BoolVar(&all, "all", false, "Remove all components or versions.")
	cmdUnInst.Flags().BoolVar(&self, "self", false, "Uninstall kmopt and clean all local data")
	return cmdUnInst
}

func removeComponents(env *environment.Environment, specs []string, all bool) error {
	for _, spec := range specs {
		paths := []string{}
		if strings.Contains(spec, ":") {
			parts := strings.SplitN(spec, ":", 2)
			// after this version is deleted, component will have no version left. delete the whole component dir directly
			if !utils.IsExist(env.LocalPath(localdata.ComponentParentDir, parts[0])) {
				return errors.Trace(fmt.Errorf("component `%s` is not installed, please use `kmopt list %s` to check", parts[0], parts[0]))
			}
			dir, err := os.ReadDir(env.LocalPath(localdata.ComponentParentDir, parts[0]))
			if err != nil {
				return errors.Trace(err)
			}
			if parts[1] == utils.NightlyVersionAlias {
				for _, fi := range dir {
					if utils.Version(fi.Name()).IsNightly() {
						paths = append(paths, env.LocalPath(localdata.ComponentParentDir, parts[0], fi.Name()))
					}
				}
			} else {
				paths = append(paths, env.LocalPath(localdata.ComponentParentDir, parts[0], parts[1]))
			}
			// if no more version left, delete the whole component dir
			if len(dir)-len(paths) < 1 {
				paths = append(paths, env.LocalPath(localdata.ComponentParentDir, parts[0]))
			}
		} else {
			if !all {
				fmt.Printf("Use `kmopt uninstall %s --all` if you want to remove all versions.\n", spec)
				continue
			}
			paths = append(paths, env.LocalPath(localdata.ComponentParentDir, spec))
		}
		for _, path := range paths {
			if !utils.IsExist(path) {
				return errors.Trace(fmt.Errorf("component `%s` is not installed, please check", spec))
			}
			fmt.Printf("Removing directory %s\n", path)
			if err := os.RemoveAll(path); err != nil {
				return errors.Trace(err)
			}
		}

		fmt.Printf("Uninstalled component `%s` successfully!\n", spec)
	}
	return nil
}
